package gzip

import (
	"bytes"
	"compress/gzip"
	"compress/zlib"
	"io"
)

type Gzip struct {
}

func (g *Gzip) Code() uint8 {
	return 1
}

func (g *Gzip) Compress(data []byte) ([]byte, error) {
	var buf *bytes.Buffer
	// buf := bytes.NewBuffer(nil)
	w := zlib.NewWriter(buf)
	defer w.Close()

	_, err := w.Write(data)
	if err != nil {
		return nil, err
	}
	err = w.Flush()
	if err != nil {
		return nil, err
	}
	if err = w.Close(); err != nil {
		return nil, err
	}

	return buf.Bytes(), nil
}

func (g *Gzip) Decompress(data []byte) ([]byte, error) {
	reader, err := gzip.NewReader(bytes.NewReader(data))
	if err != nil {
		return nil, err
	}
	defer func() {
		_ = reader.Close()
	}()
	res, err := io.ReadAll(reader)
	if err != nil {
		return nil, err
	}
	return res, nil
}
